/*
 * 版权所有(c) 刘定成(1952110078@qq.com)  2022 - 2022
 */

package com.ldc.commonlibs.common;

import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @author liudc
 * @since 2022/7/4 00:05
 */
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
    private final SparseArray<View> sparseArray = new SparseArray<>();

    public RecyclerViewHolder(@NonNull View itemView) {
        super(itemView);
    }

    /**
     * @param layoutId 视图id
     * @param parent   ViewGroup
     * @param viewType 视图类型
     * @return RecyclerViewHolder
     */
    public static RecyclerViewHolder getLayoutView(@LayoutRes int layoutId, @NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
        return getLayoutView(view);
    }

    /**
     * @param view 视图
     * @return View
     */
    public static RecyclerViewHolder getLayoutView(View view) {
        return new RecyclerViewHolder(view);
    }

    /**
     * 获取视图
     *
     * @param id 组件id
     * @return 视图
     */
    public View getView(@IdRes int id) {
        View view = sparseArray.get(id);
        if (view == null) {
            view = itemView.findViewById(id);
            sparseArray.put(id, view);
        }
        return view;
    }

    /**
     * 设置文本
     *
     * @param id   组件id
     * @param text 文本
     */
    public void setText(@IdRes int id, String text) {
        View view = getView(id);
        if (view == null) {
            return;
        }
        if (view instanceof TextView) {
            ((TextView) view).setText(text);
        }
    }

    /**
     * 设置文本
     *
     * @param id        组件id
     * @param stringRes 文本
     */
    public void setText(@IdRes int id, @StringRes int stringRes) {
        View view = getView(id);
        if (view == null) {
            return;
        }
        if (view instanceof TextView) {
            ((TextView) view).setText(stringRes);
        }
    }

    /**
     * 是否可见
     *
     * @param id   组件id
     * @param show 是否
     */
    public void setVisibility(@IdRes int id, boolean show) {
        View view = getView(id);
        if (view == null) {
            return;
        }
        view.setVisibility(show ? View.VISIBLE : View.GONE);
    }
}
